
import imghdr
import subprocess
from PIL import Image
import re

def compressImage(path,quality=None):
    imgType = imghdr.what(path)
    try:
        if imgType.lower() =='png':
            pngquant_compress(path,quality=quality)
        elif imgType.lower() in ['jpg','jpeg']:
            jpegoptim_compress(path,quality=quality )
        elif imgType.lower() =='gif':
            gifsicle_compress(path,quality=quality)
    except Exception as e:
        print(f'压缩报错:{e}')

def pngquant_compress(path, force=False, quality=None,out_path=None):
    """压缩函数.
    
    参数：
        path: 文件名称
        force: 如果存在同名文件，是否覆盖
        quality: 压缩质量。 10-40， or 10
    """
    #force_command = '-f' if force else ''
    
    quality_command = '--quality 65-80 --speed 1'
    #if quality and isinstance(quality, int):
        #quality_command = f'--quality {quality}'
    #if quality and isinstance(quality, str):
        #quality_command = f'--quality {quality}'
    if not out_path:
        command = fr'D:\tools\images\pngquant.exe {path} --skip-if-larger -f {quality_command} --output {path}'
    else:
        command = f'D:\tools\images\pngquant.exe {path} --skip-if-larger -f {quality_command} --output {out_path}' 
    #subprocess.run(command)
    print(f'压缩png图片{path}')
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #p.wait()
    #general_log.debug(p.stdout.read())
    stdout,erroutput = p.communicate()
    print(stdout)      


def jpegoptim_compress(path,quality=80):
    if not quality:
        quality = 80
    print(f'压缩jpg图片{path}')
    #command = f'jpegoptim {path} -m{quality}'
    command =fr'D:\tools\images\jpegoptim.exe --all-progressive {path} --max={quality}'
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #p.wait()
    stdout,erroutput = p.communicate()
    print(stdout)    

def gifsicle_compress(path,quality=None):
    print(f'压缩gif图片{path}')
    command = f'gifsicle -O3 {path} -o {path}'
    
    p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    #p.wait()
    stdout,erroutput = p.communicate()
    print(stdout) 



def is_progressive_jpeg(image_path):
    with Image.open(image_path) as img:
        # 检查图片格式是否为JPEG
        if img.format == 'JPEG':
            # 获取图片的信息
            info = img.info
            # 判断是否存在 'progressive' 键且其值为 True
            return info.get('progressive', False)
    return False

def change_to_jpg(path):
    img = Image.open(path)
    img = img.convert("RGB")
    file_name=  set_suffix(path,'.jpg') # f'{path}.jpg'
    img.save(file_name,quality=95)
    return file_name

def set_suffix(path,suffix):
    mt= re.search('\.\w+$',path)
    if mt:
        suffix_path = f'{path[0:-len(mt.group())]}{suffix}'
     
    else:
        suffix_path = f'{path}{suffix}'
    return suffix_path